const express = require("express");
const session = require("express-session");
const bodyParser = require("body-parser");
// 文件上传中间件
const formidableMiddleware = require("express-formidable");
const path = require("path");
const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 处理跨域，cors
app.use("*", function (req, res, next) {
  // res.header("Access-Control-Allow-Origin", "http://localhost:3000");
  res.header("Access-Control-Allow-Origin", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Content-Type, Content-Length, Authorization, Accept, X-Requested-With"
  );
  res.header("Access-Control-Allow-Methods", "PUT, POST, GET, DELETE, OPTIONS"); //设置方法
  if (req.method === "OPTIONS") {
    res.sendStatus(200); // 意思是，在正常的请求之前，会发送一个验证，是否可以请求。
  } else {
    next();
  }
});

// session配置
app.use(
  session({
    secret: "keyboard cat",
    resave: false,
    saveUninitialized: false,
  })
);

// 处理文件上传
app.use(
  "/upload",
  formidableMiddleware({
    // 文件上传目录
    uploadDir: path.join(__dirname, "upload", "avatar"),
    // 最大上传文件为2M
    maxFileSize: 2 * 1024 * 1024,
    // 保留文件扩展名
    keepExtensions: true,
  })
);

app.use("/", (req, res, next) => {
  try {
    const query = {};
    req.query
      .split("&")
      .map((item) => item.split("="))
      .forEach((item) => (query[item[0]] = item[1]));
    req.query = query;
  } catch (err) {}
  next();
});

app.use("/login", require("./src/router/login"));
app.use("/upload/avatar", require("./src/router/upload"));

app.use("/user", require("./src/router/user"));
app.use("/storage", require("./src/router/storage"));
app.use("/entity", require("./src/router/entity"));

app.use("/upload", express.static("upload"));

// 连接数据库
require("./src/model/connectDataBase.js");

app.listen(8000, () => {
  console.log("服务器启动成功，请访问 http://localhost:8000");
});
